package view

import com.jfoenix.controls.JFXPasswordField
import com.jfoenix.controls.JFXTextField
import entity.MyContract
import javafx.scene.Scene
import javafx.scene.control.Tooltip
import javafx.scene.image.Image
import javafx.scene.input.KeyCode
import javafx.scene.layout.*
import javafx.stage.Stage
import presenter.MainPresenter
import tornadofx.*
import java.io.FileInputStream

class LoginView : View() {
    val mainPresenter: MainPresenter by inject()

    override val root: StackPane by fxml()
    val userName: JFXTextField by fxid()
    val userPwd: JFXPasswordField by fxid()


    init {
        primaryStage.isResizable = true
        title = MyContract.APP_LOGIN_TITLE
        root.background = Background(
                    BackgroundImage(
                            Image(FileInputStream(MyContract.IMAGE_LOGIN_VIEW_BG)),
                            BackgroundRepeat.NO_REPEAT,
                                    BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.DEFAULT,
                            BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, false, true)
                    )
        )
        userName.setOnKeyPressed {
            if (it.code == KeyCode.ENTER) {
                userPwd.requestFocus()
            }
        }

        userPwd.setOnKeyPressed {
            if (it.code == KeyCode.ENTER) {
                loginToMainWindow()
            }
        }
    }

    @Suppress("MemberVisibilityCanBePrivate")
    fun loginToMainWindow() {
        loginToApp(userName.text, userPwd.text)
    }


    private fun loginToApp(loginUser: String, loginPwd: String) {
        mainPresenter.requestLoginToApp(loginUser, loginPwd)
    }

    fun loginSuccess() {
        showTooltips("登录成功！正在加载数据...")
//        val mainStage = Stage().apply {
//            title = MyContract.APP_MAIN_TITLE
//            setStageIcon(Image(FileInputStream(MyContract.IMAGE_VIEW_LOGO)))
//        }
//        mainStage.scene = Scene(mainView.root)
//        mainStage.show()
        replaceWith(MainWindow::class)
    }

    fun loginFailed() {
        showTooltips("登录失败，请检查用户名或密码是否正确！")
    }

    private fun showTooltips(text: String) {
        val myTooltips = Tooltip(text)

        val tooltipsx = primaryStage.x + 170
        val tooltipsy = primaryStage.y + primaryStage.height / 2

        myTooltips.show(currentWindow, tooltipsx, tooltipsy)

        runAsync {
            Thread.sleep(2000)
            ui {
                myTooltips.hide()
            }
        }
    }
}
